﻿var fs_maxWindow = false;
firstColumns = [
              { index: 0, headerText: "YTD M-1", edit: true, style: 'gray', readonly: true, width: 80, rowText: "YTDM_1" },
              { index: 2, headerText: "YTD", currentrow: true, edit: true, style: 'blue', readonly: true, width: 80, rowText: "YTD" },
              { index: 1, headerText: "Current Month", edit: true, style: '', width: 80, rowText: "CM" }
            ];




//use to VM table
function createCustomColumns(self, instance) {
    var isDisplayPage = fs.form.mode.toUpperCase() == "DISPLAY";
    var isNewPage = fs.form.mode.toUpperCase() == "NEW";
    var isControl = self.accountcode.toUpperCase() == "CONTROL";

    $(firstColumns).each(function () {
        var field = this;
        if (field.edit) {
            var v = unWarpValue(instance[field.rowText]) && !isNewPage ? unWarpValue(instance[field.rowText]) : 0.00;
            if (isNewPage)
                delete instance[field.rowText];

            if (self.withsubrow) {
                self[field.rowText] = ko.computed(function () {
                    var total = 0;
                    ko.utils.arrayForEach(self.subrow(), function (item) {
                        var value = parseFloat(unWarpValue(item[field.rowText]));
                        if (!isNaN(value)) {
                            total += value;
                        }
                    });
                    return total.toFix();
                }, self);
                self[field.rowText + "style"] = "blue";
            }
            else if (field.reference) {
                field.expression(self);
            } else { 
                self[field.rowText] = ko.observable(parseFloat(v).toFix(self.digits)); 
            }
        }

    });
    if (instance.parent.Process) {

        $(instance.parent.Process).each(function () {
            var process = this;

            var style = process.Exp.style ? process.Exp.style : "blue";
            if (process.Field == "All") {
                self.style(style);
            } else {
                style = process.Exp.mode == "search" ? style : "green";
                style = process.Exp.style ? process.Exp.style : style;

                self[process.Field + "style"] = style;
            }

            if ((!isDisplayPage) || (isDisplayPage && isControl)) {
                if (!process.Exp.selfline) {
                    var monthField = customColumns ? process.Field : "CM";
                    if (process.Budget)
                        monthField = process.Exp.month ? process.Exp.month : fs.util.getMonthByNumber(fs.form.month);
                    if (process.Forecast) {
                        monthField = "M_1";
                        process.Exp.lastmonth = true;
                    }

                    if (process.Field == "All") {
                        firstColumns.forEach(function (f) {
                            if (f.edit) {
                                expressionConnector(self, f, instance);
                            }
                        });
                    }
                    else
                        expressionConnector(self, { rowText: process.Field, month: monthField, index: fs.form.month }, instance);

                    self.style("");
                }
                else {
                    self[process.Field] = ko.computed(function () {
                        return createSelfLineFieldCalc(self, process);
                    });
                }
            }
        });
    }

    //去掉全行的样式，取每一个字段样式
    // self.style = "";
}

function createSelfLineFieldCalc(self, process) {
    var expression = "";
    self[process.Field + "style"] = "blue";
    process.Exp.fields.forEach(function (field) {
        var v = unWarpValue(self[field]);

        expression += String.format("({0}){1}", v, process.Exp.equ);
    });

    return commonAdditionCalculate(expression, self.addition, self.digits);

}

function commonAdditionCalculate(expression, addition, digits) {

    expression = expression.substring(0, expression.length - 1);

    total = fs.util.eval(expression);

    if (addition) {
        total = fs.util.eval(String.format(addition, total));
    }

    if (!isNaN(total))
        return total.toFix(digits)

    return 0.00
}

function createField(self, instance) {
    var CM = parseFloat(unWarpValue(instance["CM"])) ? parseFloat(unWarpValue(instance["CM"])) : 0.00;
    var YTDM_1 = parseFloat(unWarpValue(instance["YTDM_1"])) ? parseFloat(unWarpValue(instance["YTDM_1"])) : 0.00;
    var newFormAction = fs.form.mode == 'New';
    var editFormAction = fs.form.mode == 'Edit';
    var displsyFormAction = fs.form.mode == 'Display';

    if (typeof customColumns != "undefined" && customColumns) {
        createCustomColumns(self, instance);
        return;
    }

    instance.digits = typeof instance.digits == 'undefined' ? instance.parent.digits : instance.digits;

    self["YTDM_1"] = YTDM_1;

    if ((instance.dataFromLastMonth || instance.parent.dataFromLastMonth) && newFormAction) {
        self["YTDM_1"] = (CM + YTDM_1).toFix(instance.digits)
    }

    if (newFormAction && self.mutilFieldType) {
        self["YTDM_1"] = parseFloat(instance["YTD"]) ? parseFloat(unWarpValue(instance["YTD"])) : 0.00;
    }
    if (newFormAction) {
        self["LM"] = getLastMonthFieldData(self.accountcode, "CM");
    }
    else if (editFormAction) {
        self["LM"] = getLastMonthFieldData(self.accountcode, "CM");
        self["YTDM_1"] = getLastMonthFieldData(self.accountcode, "YTD");
    }
    if (fs.form.month == 1) {
        self["YTDM_1"] = 0;
    }

    var defaultCMCalc = function () {
        var allowCopyDataFromCM = instance.parent.allowCopyDataFromLastMonth || !newFormAction ? true : false;

        instance.defaultValue = typeof instance.defaultValue == 'function' ? instance.defaultValue() : 0;
        self["CM"] = ko.observable((allowCopyDataFromCM ? CM : instance.defaultValue).toFix(instance.digits));

        if (!newFormAction)
            self["YTD"] = ko.computed(function () {
                return (parseFloat(unWarpValue(self['YTDM_1'])) + parseFloat(unWarpValue(self['CM']))).toFix(self.digits);
            })
    }

    if (self.subrow && !instance.Process) {
        defaultCMCalc();
    }

    if (self.datarow || self.controlrow) {
        defaultCMCalc();
        if (self.Process) {
            if (!displsyFormAction) {
                expressionConnector(self, { rowText: "CM" }, instance);
                expressionConnector(self, { rowText: "YTD" }, instance);
            }
        }
    }
 
    if (instance.parent.Process && fs.form.NF) {
        defaultCMCalc();
        commonProcess(self, instance);
    }
}

function commonProcess(self, instance) {

    $(instance.parent.Process).each(function () {
        var process = this;

        self[process.Field + "style"] = "blue";

        self[process.Field] = ko.computed(function () {
            var expression = process.Exp.mutilFieldType ? process.Exp.equ : "", total = 0, index = 0;

            process.Exp.fields.forEach(function (field) {
                var endWithx = field.endWith('x');
                var identity = '';
                var fieldtype = process.Exp.fieldtype ? process.Exp.fieldtype : process.Field;
                var accountcode = instance.accountcode;

                if (process.Exp.mutilFieldType) {
                    var fieldGroup = field.split("|");
                    field = fieldGroup[1];
                    fieldtype = fieldGroup[0];
                }

                if (endWithx) {
                    var end = accountcode.substr(9, accountcode.length);
                    identity = field.substr(0, 9) + end;
                }
                else
                    identity = field;

                var v = getSubrowValueByIdentity(identity, fieldtype);
                if (process.Exp.mutilFieldType)
                    expression = expression.replace("{" + index + "}", v);
                else
                    expression += v + process.Exp.equ;

                index++;
            });

            if (!process.Exp.mutilFieldType)
            expression = expression.substring(0, expression.length - 1);

            total = fs.util.eval(expression);

            if (instance.parent.addition) {
                total = fs.util.eval(String.format(instance.parent.addition, total));
            }

            if (!isNaN(total))
                return total.toFix(instance.digits)

            return 0.00;
        });
    });

}

function subentity(instance) {
    var self = this;
    instance.description = instance.description.replace("&amp;", "&");
    self.accountcode = instance.accountcode;
    self.description = instance.description;
    self.style = ko.observable(ko.unwrap(instance.parent.style));
    self.withYTD = instance.parent.withYTD;
    self.mutilFieldType = instance.parent.mutilFieldType;
    self.entity = ko.observable(instance.entity);

    var hasParentUnit = typeof instance.parent.unit != 'undefined' && instance.parent.unit.trim() != "";
    self.unit = hasParentUnit ? instance.parent.unit : self.unit;

    if (!hasParentUnit)
        self.unit = typeof instance.unit != 'undefined' ? instance.unit : fs.form.entitycurrency;

    // self.defaultValue = instance.defaultValue;
    self.subrow = true;

    createField(self, instance);

    instance.parent.rowAfterBinding && instance.parent.rowAfterBinding(self);  
    return self;
}

var afterSearchBinding = function (items) {

    items.forEach(function (self) {

        //  if (typeof self["YTD"] == 'undefined') {
        if (!self.mutilFieldType && !self.withYTD) {
            self["YTD"] = ko.computed(function () {
                return (parseFloat(unWarpValue(self['YTDM_1'])) + parseFloat(unWarpValue(self['CM']))).toFix(self.digits);
            })

            self.rowAfterBinding && self.rowAfterBinding(self); 
        }
    });
}

function Item(instance) {
    var self = this;
    instance.description = instance.description.replace("&amp;", "&");

    self.headrow = self.emptyrow = self.datarow = self.controlrow = self.withsubrow = self.bold, self.insertcontrol = false;

    self.insertcontrol = instance.insertcontrol ? instance.insertcontrol : false;
    self.bold = instance.bold ? instance.bold : false;
    self.hide = instance.hide ? instance.hide : false;
    self.unit = instance.unit ? fs_unitMerger(instance.unit) : fs.form.entitycurrency;
    self.digits = instance.digits ? instance.digits : fs.sys.defaultDigits;

    self.rowAfterBinding = instance.rowAfterBinding;
    self.withYTD = instance.withYTD;
    self.mutilFieldType = instance.mutilFieldType;
    self.controlrow = instance.controlrow ? instance.controlrow : false;
    self.datarow = instance.datarow;
    self.Process = instance.Process;
    self.allowCopyDataFromLastMonth = instance.allowCopyDataFromLastMonth;
    self.dataFromLastMonth = instance.dataFromLastMonth;

    self.accountcode = instance.accountcode;
    self.description = instance.description;
    self.defaultValue = instance.defaultValue;
    self.addition = instance.addition;

    self.style = ko.observable(instance.style);
    self.styleInit = function (col, row) {
        if (col.hide) return "fs_disable";
        if (col.style) return col.style;
        var style = row[col.rowText + 'style'];
        col.calcfield = style ? true : false
        if (style) return style;
        if (unWarpValue(row.style)) return row.style;
        return style;
    }
    self.manual = function (col, row) {
        if (typeof row[col.rowText] == 'undefined' || fs.form.mode == 'Display' || col['readonly'])
            return false;

        var style = self.styleInit(col, row);
        return style != "blue" && style != "green";
    }

    if (instance.emptyrow) {
        self.emptyrow = instance.emptyrow;
        self.description = instance.description;
        self.accountcode = "";
        return self;
    }

    instance.parent = self;

    if (instance.subrow) {
        self.withsubrow = true;
        self.subrow = ko.observableArray([]);
        instance.subrow.forEach(function (obj) {
            obj.parent = self;
            self.subrow.push(new subentity(obj));
        });

        self.addItem = function () {
            var newAccountID = self.subrow().length;

            self.subrow.push(new subentity({ parent: instance.parent, accountcode: instance.accountcode + "-" + newAccountID, description: instance.description, subskip: instance.subskip }));
        }
        self.removeItem = function (item) {
            self.subrow.remove(item);
        }
        //self.style("blue");
    }

    if (instance.datarow||instance.controlrow) {
        createField(self, instance);
    }

    return self;
}
columnsCategory = null;

fs.util.pageLoadFunction.push(function () {

    window.viewModel = {
        entitys: fs.form.allEntity,
        categories: fs.form.allRGC,
        firstColumns: firstColumns,
        columns: firstColumns,
        columnsCategory: columnsCategory,
        items: ko.observableArray([])
    };

});